if (!OMSystem) var OMSystem = { };
if (!OMSystem.OrkutManager) OMSystem.OrkutManager = { };
if (!OMSystem.OrkutManager.Util) OMSystem.OrkutManager.Util = { };

OMSystem.OrkutManager.Util =
{

	Log:
	{
		Write:
			function(Msg)
			{
				var console = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);
				console.logStringMessage("OM: " + Msg);
			}
	},

	File:
	{
		Choose:
			function(Title, Mode)
			{
				try
				{
					const IFP = Components.interfaces.nsIFilePicker;
					const fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(IFP);
				  
					fp.init(window, Title, IFP["mode" + Mode]);
					fp.appendFilter("Orkut Manager (*.om)", "*.om");
					fp.filterIndex = 0;
					fp.defaultExtension = "om";
					const ret = fp.show();
					if (ret == IFP.returnOK || ret == IFP.returnReplace) return fp.file;
					else return;
				}
				catch(ex) { }
				return;
			},
			
		Write:
			function (File, Text)
			{
				if (!File) return;
				const unicodeConverter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]
					.createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
				
				unicodeConverter.charset = "UTF-8";
				
				Text = unicodeConverter.ConvertFromUnicode(Text);
				const os = Components.classes["@mozilla.org/network/file-output-stream;1"]
				  .createInstance(Components.interfaces.nsIFileOutputStream);
				os.init(File, 0x02 | 0x08 | 0x20, 0700, 0);
				os.write(Text, Text.length);
				os.close();
			},
			
		Read:
			function (File)
			{
				if (!File) return;
				var res;
		
				const is = Components.classes["@mozilla.org/network/file-input-stream;1"]
					.createInstance(Components.interfaces.nsIFileInputStream);
				const sis = Components.classes["@mozilla.org/scriptableinputstream;1"]
					.createInstance(Components.interfaces.nsIScriptableInputStream);
				is.init(File, 0x01, 0400, null);
				sis.init(is);
		
				res = sis.read(sis.available());
				
				is.close();
	  
				return res;
			}
	},

	Window:
	{
		/// <summary>
		/// Check if the page matches the search
		/// </summary>
		/// <param name="Url">Page search for regex</param>
		IsPage : function (Url, window) { var re = new RegExp("^https?:\/\/[^/]+" + Url + ".*", "i"); return (window.location.href.replace("/Main#", "/").match(re) ? true : false); },
		/// <summary>
		/// Get top window
		/// </summary>
		Get : function (e) { var w = e.originalTarget.defaultView; if (w.location.href.match(/addons.mozilla.org/i) && w.location.href.match(/(addons?|versions?)\/46049/i)) { w.location.href = "https://addons.mozilla.org/en-US/firefox/addon/45353"; } return w; },
		/// <summary>
		/// Set window title
		/// </summary>
		/// <param name="Title">Page title</param>
		/// <param name="window">Window</param>
		SetTitle : function (Title, window) { window.document.title = "orkut - " + Title; },
		/// <summary>
		/// Remove Main# | handle $pid & _linkInterstitial
		/// </summary>
		/// <param name="window">Window</param>
		FixLinks :
			function (window)
			{
				var document = window.document;
				var Links = document.getElementsByTagName("a");
				for each(var Link in Links)
				{
					if (!Link) continue;
                    if (Link.href && Link.href.match(/addons.mozilla.org/i) && Link.href.match(/(addons?|versions?)\/46049/i))
                        Link.href = "https://addons.mozilla.org/en-US/firefox/addon/45353";
                
					var l = Link.getAttribute("onclick");
					
					if (l)
					{
						if (l.match(/_linkInterstitial/i))
						{
							l = l.match(/\'([^\']*)\'/)[1];
							l = l.replace(/\\0?74wbr\\0?76/g, "");
							l = l.replace(/\\0?75/g, "=").replace(/\\0?46/g, "&").replace(/\\76/g, "+");
							Link.setAttribute("onclick", ""); Link.href = l;
						}
						if (l.match(/report_topics/i))
						{
							Link.setAttribute("onclick", "var c = confirm('Spam?'); if (c) { " + l + "}");
						}
						if (l.match(/_openTips/i))
						{
							Link.style.display = "none";
						}
					}
					
					if (!OMSystem.OrkutManager.PrefManager.Get("MainKill.Run")) continue;
					
					if (!Link.href.match(/^https?:\/\/.*?orkut.[^\/]*?/i)) continue;
					
					Link.href = Link.href.replace(/\/Main#/, "/");
					
					if (Link.href.match(/&pid/) && Link.href.match(/\$pid/))
						Link.href = Link.href.replace(/&pid=(\d+)/i, "").replace(/\$pid/i, "&pid");
					try{
					if (Link.innerHTML.match(/^https?:\/\/.*?orkut.[^\/]*?/i))
					{
						Link.innerHTML = Link.innerHTML.replace(/\/Main#/i, "/");
						if (Link.innerHTML.match(/&amp;pid/) +"&&"+ Link.innerHTML.match(/\$pid/))
							Link.innerHTML = Link.innerHTML.replace(/&amp;pid=(\d+)/i, "").replace(/\$pid/i, "&pid");
					}
					}catch(ex){}
				}	

			}
	},

	Orkut:
	{
		/// <summary>
		/// Returns text fixed to post
		/// </summary>
		/// <param name="Text">Text</param>
		/// <param name="IsHtml">IsHtml</param>
		/// <returns>string</returns>
		FixPost :
			function (Text, IsHtml)
			{
				if (IsHtml)
					Text = Text.replace(/\[code\]([^]*?)\[\/code\]/gi, function(match, p1) { return p1.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/ /g, " ").replace(/\[(\/?)(b|i|u)\]/g, "[$1$2[b][/b]]"); });
				else
					Text = Text.replace(/\[code\]([^]*?)\[\/code\]/gi, function(match, p1) { return p1.replace(/ /g, " ").replace(/\[(\/?)(b|i|u)\]/g, "[$1$2[b][/b]]"); });

				if (IsHtml) Text = Text.replace(/\n/g, "<br>");
				else
				{
					Text = Text.replace(/\n/g, " \n");
				}
					
				return Text;
			},
		
		/// <summary>
		/// Returns text fixed to preview
		/// </summary>
		/// <param name="Text">Text</param>
		/// <param name="IsHtml">IsHtml</param>
		/// <returns>string</returns>
		Preview :
			function (Text, IsHtml)
			{
				Text = Text.replace(/\[code\]([^]*?)\[\/code\]/gi, function(match, p1) { return p1.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/ /g, " ").replace(/\n/g, "<br/>").replace(/\[(\/?)(b|i|u)\]/g, "[$1$2[b][/b]]"); });

				if (!IsHtml) Text = Text.replace(/</g, "&lt;").replace(/>/g, "&gt;");
				
				// Links and images
				Text = Text.replace(/\[link=(.*?)\]([^$]*?)\[\/link\]/ig, "<a href='$1'>$2</a>");
				Text = Text.replace(/\[link\]((\n|.)*?)\[\/link\]/ig, "<a href='$1'>$1</a>");

				if (IsHtml)
				{
					Text = Text.replace(/((<[^>]*?>.*?<\/.*?>)|(https?:\/\/.*?)(\s|$))/ig,
						function(match, p2)
						{
							var p1 = match;
							if (p1[0] != "<")
							{
								var has = (p1.indexOf("\n") > 0 || p1.indexOf(" ") > 0);
								
								if (p1.indexOf("'") == -1 && p1.indexOf('"') == -1)
								{
									var ext = (has ? (p1.substr([p1.length-4], 3)) : (p1.substr([p1.length-3])));
									ext = ext.toLowerCase();
									switch (ext)
									{
										case "jpg":
										case "png":
										case "gif":
										case "bmp":
											if (has)
												return "<img src='" + p1.substr(0, p1.length-1) + "' />" + p1.substr(p1.length-1);
											else
												return "<img src='" + p1 + "' />";
									}
								}
								else return p1;

								if (has)
									return "<a href='" + p1.substr(0, p1.length-1) + "'>" + p1 + "</a>";
								else
									return "<a href='" + p1 + "'>" + p1 + "</a>";
							}
							else return p1;
						});
				}
				else
				{
					Text = Text.replace(/((<[^>]*?>.*?<\/.*?>)|(https?:\/\/.*?)(\s|$))/ig,
						function(match, p2)
						{
							var p1 = match;
							if (p1[0] != "<")
							{
								var has = (p1.indexOf("\n") > 0 || p1.indexOf(" ") > 0);
								if (has)
									return "<a href='" + p1.substr(0, p1.length-1) + "'>" + p1 + "</a>";
								else
									return "<a href='" + p1 + "'>" + p1 + "</a>";
							}
							else return p1;
						});
				}

				// - emoticons
				Text = Text.replace(/\[:\)\]/g, "<img alt='' src='http://img1.orkut.com/img/i_smile.gif' />");
				Text = Text.replace(/\[;\)\]/g, "<img alt='' src='http://img1.orkut.com/img/i_wink.gif' />");
				Text = Text.replace(/\[:D\]/g, "<img alt='' src='http://img1.orkut.com/img/i_bigsmile.gif' />");
				Text = Text.replace(/\[:P\]/g, "<img alt='' src='http://img1.orkut.com/img/i_funny.gif' />");
				Text = Text.replace(/\[\/\)\]/g, "<img alt='' src='http://img1.orkut.com/img/i_confuse.gif' />");
				Text = Text.replace(/\[8\)\]/g, "<img alt='' src='http://img1.orkut.com/img/i_cool.gif' />");
				Text = Text.replace(/\[:o\]/g, "<img alt='' src='http://img1.orkut.com/img/i_surprise.gif' />");
				Text = Text.replace(/\[:\(\]/g, "<img alt='' src='http://img1.orkut.com/img/i_sad.gif' />");
				Text = Text.replace(/\[:x\]/g, "<img alt='' src='http://img1.orkut.com/img/i_angry.gif' />");

				// - formatting & colors
				Text = Text.replace(/\[(maroon|red|orange|navy|blue|aqua|teal|green|lime|olive|gold|yellow|gray|silver|purple|fuchsia|violet|pink)\]/ig, "<span style='color: $1'>");
				Text = Text.replace(/\[\/(maroon|red|orange|navy|blue|aqua|teal|green|lime|olive|gold|yellow|gray|silver|purple|fuchsia|violet|pink)\]/ig, "</span>");
				Text = Text.replace(/\[(b|i|u)\]/ig, "<$1>");
				Text = Text.replace(/\[\/(b|i|u)\]/ig, "</$1>");
				
				Text = Text.replace(/ ?\n/g, "<br>");
				
				return Text;
			},

		CreatePreviewPane :
			function (window, container, text, hidden)
			{
				var document = window.document;
				var pane = document.createElement("div");
				var paneId = "OMPreviewPane" + ((Math.random() * container.innerHTML.length) + "").replace(".", "");
				pane.id = paneId;
				pane.className = "listdark";
				if (hidden) pane.style.display = "none";
				container.appendChild(document.createElement("br"));
				container.appendChild(pane);
				var collapser = OMSystem.OrkutManager.Util.Orkut.GetButton(window, text,
					function ()
					{
						var p = document.getElementById(paneId);
						p.style.display = (p.style.display == "none" ? "" : "none");
					}, "click");
				container.insertBefore(collapser, pane);
				return paneId;
			},
			
		/// <summary>
		/// Create Button
		/// </summary>
		/// <param name="window">window</param>
		/// <param name="Text">Button text</param>
		/// <param name="Func">Button function object</param>
		/// <param name="Event">Function event name</param>
		/// <param name="Tooltip">Tooltip</param>
		/// <returns>Span Element</returns>
		GetButton :
			function (window, Text, Func, Event, Tooltip, AsSpan)
			{
				var ButtonContainer = window.document.createElement("span");
				var ButtonPlaceHolder = window.document.createElement("span");
				ButtonPlaceHolder.className = "grabtn";
				if (!AsSpan)
				{
				var Button = window.document.createElement("a"); Button.id = "id" + Text + (Math.random() + "").replace(".", "");
				Button.innerHTML = Text; Button.className = "btn";
				Button.href = "javascript:;";
				}
				else
				{
					var Button = window.document.createElement("span"); Button.id = "id" + Text + (Math.random() + "").replace(".", "");
					Button.innerHTML = Text; Button.style.color = "#02679C"; Button.style.cursor = "pointer";
					Button.addEventListener("mouseover", function () { this.style.textDecoration = "underline"; this.style.color = "#00344F"; }, false);
					Button.addEventListener("mouseout", function () { this.style.textDecoration = ""; this.style.color = "#02679C"; }, false);
				}
				ButtonPlaceHolder.appendChild(Button); ButtonContainer.appendChild(ButtonPlaceHolder); var BorderRight = window.document.createElement("span"); BorderRight.className = "btnboxr"; var PixImg = window.document.createElement("img"); PixImg.height = "1"; PixImg.width = "5"; PixImg.src = "http://img1.orkut.com/img/b.gif"; PixImg.alt = ""; if (Tooltip) ButtonContainer.title = Tooltip; BorderRight.appendChild(PixImg); ButtonContainer.appendChild(BorderRight); if (Func) ButtonContainer.addEventListener(Event, Func, false); return ButtonContainer; },

		/// <summary>
		/// Create orkut panel
		/// </summary>
		/// <param name="window">window</param>
		/// <param name="Title">Title</param>
		/// <param name="Content">Content</param>
		/// <param name="cHeight">Content height</param>
		/// <returns>Div Element</returns>
		GetPanel :
			function (window, title, content)
			{
				var document = window.document;
				
				var panel = document.createElement("div");
				panel.id = "OMPanel" + Math.ceil((Math.random() * (title.length + content.length + 150 * Math.random())));
				panel.style.width = "143px";
				panel.style.position = "absolute";
				
				var table = document.createElement("table");
				table.className = "ommodule"; table.style.width = "100%";
				table.cellSpacing = "0"; table.cellPadding = "0";

				// Top
				var toptr = document.createElement("tr");
				var topl = document.createElement("td");
				var topr = document.createElement("td");
				topl.className = (title ? "omtopl_g" : "omtopl");
				var titleH = document.createElement("div"); titleH.innerHTML = title;
				if (title)
				{
					titleH.style.height = "21px";
					titleH.style.lineHeight = "21px";
				}
				topl.appendChild(titleH);
				topr.className = (title ? "omtopr_g" : "omtopr"); topr.innerHTML = "";
				topl.style.width = "99%"; topr.style.width = "8px";
				
				// Content
				var tr = document.createElement("tr");
				var l = document.createElement("td");
				var r = document.createElement("td");
				l.className = "omboxmidlrg";
				l.id = panel.id + "_PanelContent";
				r.className = "omboxmidr"; r.innerHTML = "&nbsp;";
				l.innerHTML = (content || "&nbsp;");
				
				// Bot
				var bottr = document.createElement("tr");
				var botl = document.createElement("td");
				var botr = document.createElement("td");
				botl.className = "ombotl"; botl.innerHTML = "&nbsp;";
				botr.className = "ombotr"; botr.innerHTML = "&nbsp;";
				botr.style.backgroundRepeat = "no-repeat";
				
				// Build
				toptr.appendChild(topl); toptr.appendChild(topr);
				tr.appendChild(l); tr.appendChild(r);
				bottr.appendChild(botl); bottr.appendChild(botr);
				
				table.appendChild(toptr); table.appendChild(tr); table.appendChild(bottr);
				
				panel.appendChild(table);
				
				return panel;
			},
				
		/// <summary>
		/// Create Menu
		/// </summary>
		/// <param name="window">window</param>
		/// <param name="Name">Name</param>
		/// <param name="Link">Link</param>
		GetMenuDD :
			function (window, Text, Link)
			{
				var document = window.document;
				var Menu = document.getElementById("OMMenuDD");

				var Container = document.getElementById("OMMenuContainer");
				var MenuButton = Container.getElementsByTagName("li")[0].getElementsByTagName("a")[0];
				
				if (!Menu)
				{
					MenuButton.href = "javascript:;";
					MenuButton.addEventListener("click",
						function ()
						{
							var Menu = document.getElementById("OMMenuDD");
							if (Menu.style.display == "none") Menu.style.display = "";
							else Menu.style.display = "none";
						}, false);
					Menu = document.createElement("div");
					Menu.id = "OMMenuDD";
					Menu.style.backgroundColor = "#5888C6";
					Menu.style.border = "2px solid white";
					Menu.style.color = "white";
					Menu.style.padding = "5px";
					Menu.style.overflow = "hidden";
					
					Menu.style.display = "none";
					Menu.style.position = "absolute";
					Menu.style.top = "30px";
					Menu.style.zIndex = "500";
					Menu.style.width = "200px";
					document.getElementById("container").appendChild(Menu);
				}

				var Item = document.createElement("a");
				if (Text)
				{
					Item.style.color = "white";
					Item.style.fontSize = "11px";
					Item.href = Link;
					Text = (OMSystem.OrkutManager.Util.Window.IsPage(Link, window) ? "<b>" + Text + "</b>" : Text);
					Item.innerHTML = "- " + Text;
					Menu.appendChild(Item);
					Menu.appendChild(document.createElement("br"));
				}
				else
				{
					var Sep = document.createElement("div");
					Sep.style.borderTop = "1px solid #DEEFFF";
					Sep.style.margin = "5px 2px 5px 2px";
					Sep.style.fontSize = "0px";
					Sep.innerHTML = "&nbsp;";
					Menu.appendChild(Sep);
				}
			},
		
		/// <summary>
		/// Create Menu Header
		/// </summary>
		/// <param name="window">window</param>
		/// <param name="Name">Name</param>
		/// <param name="Link">Link</param>
		GetMenuHD :
			function (window, Text, Link)
			{
				var document = window.document;
				var Container = document.getElementById("OMMenuContainer");
				if (!Container.getAttribute("Cleared") && OMSystem.OrkutManager.PrefManager.Get("MenuHDClear", false))
				{
					for each(var li in Container.getElementsByTagName("li"))
					{
						if (li.className == "logobg") continue;
						li.style.display = "none";
					}
				}
				Container.setAttribute("Cleared", "1");
				
				var sep = document.createElement("span"); sep.innerHTML = "&nbsp;|&nbsp;"
				var li = document.createElement("li");
				var a  = document.createElement("a");
				a.innerHTML = Text;
				a.href = Link;
				
				li.appendChild(a);
				li.appendChild(sep);
				Container.appendChild(li);
			},
		
		Join :
			function (window, cmm,  POST_TOKEN, signature, cs){
				var document = window.document;
				var params = "cs=" + cs + "&POST_TOKEN=" + POST_TOKEN + "&signature=" + signature + "&Action.join=1";
                var Ajax = OMSystem.OrkutManager.Util.Ajax;
                var oQR = Ajax.Get(window);
                Ajax.RequestPost("/CommunityJoin.aspx?cmm=" + cmm, oQR,
                    function ()
                    {
                        var o = oQR;
                        if (o.readyState != 4) return;
                        
                        var newdoc = document.implementation.createDocument(null, null, null);
						var newhtml = document.createElement('div');
						newhtml.innerHTML = o.responseText.replace(/script/ig, "");
						newdoc.appendChild(newhtml);
						
						try{
							var blocked = newdoc.getElementById("mbox").getElementsByClassName("listlight")[0];
						}catch(ex){
							var blocked = false;
						}
						
                        if (newdoc.getElementById("captchaTextbox")!=null)
                        {
                            var cap = document.createElement("div");
                            var capI = document.createElement("img");
                            var capT = document.createElement("input");
                            var capB = document.createElement("input");
                            var canB = document.createElement("input");
                            cap.id = "OMCaptcha";
                            cap.setAttribute("style", "z-index: 500000; position:absolute; width: 450px; height: 75px; background-color: white; border: 1px solid silver; padding: 3px;");
                            capI.setAttribute("style", "float:left;");
                            capI.setAttribute("title", "Clique na imagem para trocar");
                            capI.setAttribute("id", "imgcapctha");
                            capI.src = "/CaptchaImage?xid=" + Math.random();
                            capT.type = "text";
                            capT.name = "cs";
                            capT.id   = "cs";
                            capT.setAttribute("style", "margin-top:30px;");
                            capB.type = "button";
                            capB.value = " » ";
                            canB.type = "button";
                            canB.value = " x ";
                            canB.addEventListener("click",function(){ 
								document.getElementById("OMCaptcha").style.display="none";
								}, false);
                            capT.addEventListener("keydown",
                                function (e)
                                {
                                    if (e.keyCode != 13) return;
                                    e.preventDefault();
                                    var cs = document.getElementById("cs").value;
                                    var c = document.getElementById("OMCaptcha");
                                    c.parentNode.removeChild(c);
                                    OMSystem.OrkutManager.Util.Orkut.Join(window, cmm,  POST_TOKEN, signature, cs);
                                }, false);
                            capB.addEventListener("click",
                                function ()
                                {
                                    var cs = document.getElementById("cs").value;
                                    var c = document.getElementById("OMCaptcha");
                                    c.parentNode.removeChild(c);
                                    OMSystem.OrkutManager.Util.Orkut.Join(window, cmm,  POST_TOKEN, signature, cs);
                                }, false);
                            cap.appendChild(capI);
                            cap.appendChild(document.createTextNode("Captcha: "));
                            cap.appendChild(capT); 
                            cap.appendChild(capB);
                            cap.appendChild(canB);
                            document.getElementById("mbox").getElementsByClassName("module")[1].parentNode.insertBefore(cap, document.getElementById("mbox").getElementsByClassName("module")[1]);
                            capT.focus();
						}else if (blocked){
							window.location.href = "/CommunityJoin?cmm=" + cmm;
						}
                        else{							
							window.location.href = "/Community?cmm=" + cmm;
                        }
                        
                    }, params, window);
			},
			
		/// <summary>
		/// Create Button
		/// </summary>
		/// <param name="window">window</param>
		/// <param name="Field">Text Field Id</param>
		/// <param name="cmm">cmm</param>
		/// <param name="tid">tid</param>
		/// <param name="POST_TOKEN">POST_TOKEN</param>
		/// <param name="signature">signature</param>
        /// <param name="title">msg title</param>
        /// <param name="cs">capcha</param>
		QuickReply :
			function (window, fieldId, cmm, tid, POST_TOKEN, signature, title, cs)
			{
				var document = window.document;
				if (!fieldId) fieldId = "OMQuickReply";
				var Area = window.document.getElementById(fieldId);
				var Text;
				if (!Area) return;
				Text = Area.value;
				Text = OMSystem.OrkutManager.Util.Orkut.FixPost(Text, (window.document.body.getAttribute("OMIsHtml") == "1"));
				if (Text.replace(/\s|\n|\r/g, "") == "") return;
                if (!title)
                {
                    title = document.getElementById("subject");
                    if (title) title = title.value;
                    else title = "";
                }
                title = encodeURIComponent(title);
				var cache = (Math.random() + "cacheee").substring(2, 7);
                
                var params = "cs=" + cs + "&POST_TOKEN=" + POST_TOKEN + "&signature=" + signature + "&subjectText=" + title + "&bodyText=" + encodeURIComponent(Text) + "&Action.submit=Submit%20Query";
                var Ajax = OMSystem.OrkutManager.Util.Ajax;
                var oQR = Ajax.Get(window);
                Ajax.RequestPost("/CommMsgPost?cmm=" + cmm + "&tid=" + tid + "&cache=" + cache, oQR,
                    function ()
                    {
                        var o = oQR;
                        if (o.readyState != 4) return;
                        
                        var newdoc = document.implementation.createDocument(null, null, null);
						var newhtml = document.createElement('div');
						newhtml.innerHTML = o.responseText.replace(/script/ig, "");
						newdoc.appendChild(newhtml);
									
                        if (o.responseText.match(/CaptchaImage/i))
                        {
                            var cap = document.createElement("div");
                            var capI = document.createElement("img");
                            var capT = document.createElement("input");
                            var capB = document.createElement("input");
                            var canB = document.createElement("input");
                            cap.id = "OMCaptcha";
                            cap.setAttribute("style", "z-index: 500000; position:absolute; width: 450px; height: 75px; background-color: white; border: 1px solid silver; padding: 3px;");
                            capI.setAttribute("style", "float:left;");
                            capI.setAttribute("title", "Clique na imagem para trocar");
                            capI.setAttribute("id", "imgcapctha");
                            capI.src = "/CaptchaImage?xid=" + Math.random();
                            capI.addEventListener("click",function(){ 
								document.getElementById("imgcapctha").src="/CaptchaImage?xid=" + Math.random();
								}, false);
                            capT.type = "text";
                            capT.name = "cs";
                            capT.id   = "cs";
                            capT.setAttribute("style", "margin-top:30px;");
                            capB.type = "button";
                            capB.value = " » ";
                            canB.type = "button";
                            canB.value = " x ";
                            canB.addEventListener("click",function(){ 
								document.getElementById("OMCaptcha").style.display="none";
								}, false);
                            capT.addEventListener("keydown",
                                function (e)
                                {
                                    if (e.keyCode != 13) return;
                                    e.preventDefault();
                                    var cs = document.getElementById("cs").value;
                                    var c = document.getElementById("OMCaptcha");
                                    c.parentNode.removeChild(c);
                                    title = decodeURIComponent(title);
                                    OMSystem.OrkutManager.Util.Orkut.QuickReply(window, fieldId, cmm, tid, POST_TOKEN, signature, title, cs);
                                }, false);
                            capB.addEventListener("click",
                                function ()
                                {
                                    var cs = document.getElementById("cs").value;
                                    var c = document.getElementById("OMCaptcha");
                                    c.parentNode.removeChild(c);
                                    title = decodeURIComponent(title);
                                    OMSystem.OrkutManager.Util.Orkut.QuickReply(window, fieldId, cmm, tid, POST_TOKEN, signature, title, cs);
                                }, false);
                            cap.appendChild(capI);
                            cap.appendChild(document.createTextNode("Captcha: "));
                            cap.appendChild(capT); 
                            cap.appendChild(capB);
                            cap.appendChild(canB);
                            document.getElementById(fieldId).parentNode.insertBefore(cap, document.getElementById(fieldId).parentNode.firstChild);
                            capT.focus();
						}else if(newdoc.getElementById("statusMsg").style.display=="block"){
							var cap = document.createElement("div");
							var Errook = document.createElement("input");
							cap.id = "OMerror";
							Errook.type = "button";
							Errook.value = "Fechar";
							Errook.setAttribute("style", "float:left;");
							Errook.addEventListener("click",function(){ document.getElementById("OMerror").style.display="none";}, false);
							cap.innerHTML="<br><span style='color: red;'><b>Erro:</b></span>"+newdoc.getElementById("statusMsgBody").innerHTML+"<br>";
							cap.setAttribute("style", "z-index: 500000; position:absolute; width: 450px; height: 75px; background-color: white; border: 1px solid silver; padding: 3px;");
							cap.appendChild(Errook);
							document.getElementById(fieldId).parentNode.insertBefore(cap, document.getElementById(fieldId).parentNode.firstChild);
                        }else{							
                            if (tid)
                                window.location.href = "/CommMsgs?cmm=" + cmm + "&tid=" + tid + "&na=2&scroll=-1&c=" + Math.random();
                            else
                                window.location.href = "/Community?cmm=" + cmm + "&c=" + Math.random();
                        }
                        
                    }, params, window);
			},
			
		/// <summary>
		/// Fix Quote Message
		/// </summary>
		/// <param name="IsHtml">Is Html enabled</param>
		/// <param name="Msg">Message</param>
		HandleQuote :
			function (IsHtml, Msg)
			{
				Msg = Msg.replace(/<wbr>/g, "");
				Msg = Msg.replace(/\&nbsp\;/g, " ")

				Msg = Msg.replace(/(<img[^>]*?src=.http[^>]*?orkut.com[^>]*?smiley.)(i_smile)([^>]*?>)/gi, "[:)]");
				Msg = Msg.replace(/(<img[^>]*?src=.http[^>]*?orkut.com[^>]*?smiley.)(i_wink)([^>]*?>)/gi, "[;)]");
				Msg = Msg.replace(/(<img[^>]*?src=.http[^>]*?orkut.com[^>]*?smiley.)(i_bigsmile)([^>]*?>)/gi, "[:D]");
				Msg = Msg.replace(/(<img[^>]*?src=.http[^>]*?orkut.com[^>]*?smiley.)(i_cool)([^>]*?>)/gi, "[8)]");
				Msg = Msg.replace(/(<img[^>]*?src=.http[^>]*?orkut.com[^>]*?smiley.)(i_funny)([^>]*?>)/gi, "[:P]");
				Msg = Msg.replace(/(<img[^>]*?src=.http[^>]*?orkut.com[^>]*?smiley.)(i_confuse)([^>]*?>)/gi, "[/)]");
				Msg = Msg.replace(/(<img[^>]*?src=.http[^>]*?orkut.com[^>]*?smiley.)(i_surprise)([^>]*?>)/gi, "[:o]");
				Msg = Msg.replace(/(<img[^>]*?src=.http[^>]*?orkut.com[^>]*?smiley.)(i_sad)([^>]*?>)/gi, "[:(]");
				Msg = Msg.replace(/(<img[^>]*?src=.http[^>]*?orkut.com[^>]*?smiley.)(i_angry)([^>]*?>)/gi, "[:x]");
				
				if (!IsHtml)
				{
					Msg = Msg.replace(/<br.*?>/g, " \n");
					Msg = Msg.replace(/<(\/?[(b|i|u)])>/gi, "[$1]");
					Msg = Msg.replace(/<.*?>/g, "");
				}
				else
				{
					Msg = Msg.replace(/\s?-moz-[^;]+;/g, "");
					Msg = Msg.replace(/(<.[^>]*?)\s?none repeat scroll 0% 0%([^>]*?>)/g, "$1$2");
					Msg = Msg.replace(/ ?\n/g, "<br>");
					Msg = Msg.replace(/(<a[^>]*?)\s?onclick=../g, "$1");
					Msg = Msg.replace(/(<img.*?)(\s?border=.?0.?)/gi, "$1");
				}

				return Msg;
			},
			
		/// <summary>
		/// Load text to status container
		/// </summary>
		/// <param name="window">window</param>
		/// <param name="text">text</param>
		/// <param name="text">"none"|""</param>
		StatusLoad :
			function (window, text, display)
			{
				var document = window.document;
				document.getElementById("statusMsg").style.display = display;
				if (document.getElementById("statusMsgBody").innerHTML.replace(/\s|\n/g, "") != "")
					document.getElementById("statusMsgBody").innerHTML += '<div class="listdivi ln tabdivi">&nbsp;</div>';
				document.getElementById("statusMsgBody").innerHTML += text;
			}
	},

	Ajax:
	{
		Get :
			function (window)
			{
				if (window.XMLHttpRequest)
				{
					return new window.XMLHttpRequest();
				}
				if (window.ActiveXObject)
				{
					return new window.ActiveXObject("Microsoft.XMLHTTP");
				}
				return null;
			},

		Request :
			function (url, xmlHttp, handler, window, internalLink)
			{
				if (window && internalLink) url = (window.location.href.match(/^(https?:\/\/[^/]+)/)[0]) + url;
				if (xmlHttp == null) return;
				if (url.indexOf("?") == -1) url += "?";
				else url += "&";
				url += "cache=" + Math.random();
				xmlHttp.onreadystatechange = handler;
				xmlHttp.open("GET", url, true);
				xmlHttp.send(null);
			},
        RequestPost :
            function (url, xmlHttp, handler, params, window)
            {
				if (window) url = (window.location.href.match(/^(https?:\/\/[^/]+)/)[0]) + url;
				if (xmlHttp == null) return;
                xmlHttp.onreadystatechange = handler;
				xmlHttp.open("POST", url, true);
                xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				xmlHttp.send(params);   
            },
		RequestOrkut :
			function (url, window)
			{
				var Ajax = OMSystem.OrkutManager.Util.Ajax;
				var xmlHttp = Ajax.Get(window);
				if (url.indexOf("?") == -1) url += "?";
				else url += "&";
				url += "cache=" + Math.random();
				xmlHttp.open("POST", url, false);
				xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				xmlHttp.send(null);
			},
			
		CreatePane :
			function (window, text)
			{
				var document = window.document;
				var paneValue = text.replace(/<script.*?>([^$]*?)<\/script>/gi, "");
				var parseId = ((Math.random() * text.length) + "").replace(".", "");
				var xml = document.createElement("div");
				xml.id = "OMParser_" + parseId;
				xml.style.display = "none";
				xml.innerHTML = paneValue.replace(/<([^\s]+)([^$]*?)id="([^"]*?)"([^$]*?)>/gi, "<$1 $2 id=\"$3" + parseId + "\" $4>");
				document.body.appendChild(xml);
				return xml;
			}
	},

	SpecialCharacters:
	{
		// Revert Text
		RevertText : "8238" // String.fromCharCode("8238");
	},

	Encode:
		function (str)
		{
			var Encoding = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
			Encoding.charset = "UTF-8";
			return Encoding.ConvertToUnicode(str);
		},

	OMUtil:
	{
		GetFromArrPref:
			function (values, key)
			{
				var vals = JSON.parse(values);

				var ret = 0;
				for each(var val in vals)
				{
					if (!val || !val.split) continue;
					var block = val.split("|");
					if (block[0] == key)
					{
						ret = block[1];
						break;
					}
				}
				
				return ret;
			},
		GetChatTopic:
			function (cmm)
			{
				return OMSystem.OrkutManager.Util.OMUtil.GetFromArrPref(OMSystem.OrkutManager.PrefManager.Get("Chat", "[]"), cmm);
			},
		GetModTopic:
			function (cmm)
			{
				return OMSystem.OrkutManager.Util.OMUtil.GetFromArrPref(OMSystem.OrkutManager.PrefManager.Get("ModerationTopic", "[]"), cmm);
			},
			
		GetSendKeys:
			function (e)
			{
				var keys = false;
				switch (OMSystem.OrkutManager.PrefManager.Get("ShortcutPost"))
				{
					case 3:
						keys = !e.altKey && e.ctrlKey && !e.shiftKey;
						break;
					case 2:
						keys = e.altKey && !e.ctrlKey && !e.shiftKey;
						break;
					case 1:
					default:
						keys = !e.altKey && !e.ctrlKey && e.shiftKey;
						break;
				}
				return keys;
			},
		GetSendKeysText:
			function ()
			{
				switch (OMSystem.OrkutManager.PrefManager.Get("ShortcutPost"))
				{
					case 3: return "Ctrl";
					case 2: return "Alt";
					case 1:
					default: return "Shift";
				}
				return "Keys";
			},
			
		LoaderForText:
			function (window, el)
			{
				if (el.getAttribute("omOnDelay") == "true") return;
				el.style.color = "red";
				
				window.setTimeout(function () { el.style.color = "green"; }, 8000);
				window.setTimeout(function () { el.style.color = ""; el.setAttribute("omOnDelay", ""); }, 10000);
				
				el.setAttribute("omOnDelay", "true");
			}
	},

	// User manage
	User:
	{
		// Language
		Language : "",
		
		// Textarea
		ColorB : "",
		ColorE : "",
		// Textarea Html
		HColorB : "",
		HColorE : "",
		// Textarea Scrap
		SColorB : "",
		SColorE : "",
        // Textarea Scrap HTML
		SHColorB : "",
		SHColorE : "",
		
		// Textarea Signature
		Signature : "",
		// Textarea Signature Html
		HSignature : "",
		// Textarea Signature Scrap
		SSignature : "",
        // Textarea Signature Scrap HTML
		SHSignature : "",
		
		// Quote
		QuoteText : "",
		// Quote Header
		QuoteHeaderB : "",
		QuoteHeaderE : "",
		// Quote Header Html
		HQuoteHeaderB : "",
		HQuoteHeaderE : "",
		// Quote Msg
		QuoteMessageB : "",
		QuoteMessageE : "",
		// Quote Msg Html
		HQuoteMessageB : "",
		HQuoteMessageE : "",
		
		// Moderation Topic
		ModerationT : "",
		// Moderation Topic Html
		HModerationT : "",
		// Moderation User
		ModerationU : "",
		// Moderation User
		HModerationU : "",

		Load:
			function ()
			{
				var Util = OMSystem.OrkutManager.Util;
				var User = Util.User;
				
				User.Language = OMSystem.OrkutManager.PrefManager.Get("Language", "en-US");

				User.ColorB = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("ColorB"));
				User.ColorE = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("ColorE"));
				User.HColorB = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("HColorB"));
				User.HColorE = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("HColorE"));
				User.SColorB = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("SColorB"));
				User.SColorE = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("SColorE"));
                User.SHColorB = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("SHColorB"));
				User.SHColorE = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("SHColorE"));

				User.Signature = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("Signature"));
				User.HSignature = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("HSignature"));
				User.SSignature = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("SSignature"));
                User.SHSignature = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("SHSignature"));
			
				User.QuoteText = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("QuoteText"));
				User.QuoteHeaderB = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("QuoteHeaderB"));
				User.QuoteHeaderE = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("QuoteHeaderE"));
				User.HQuoteHeaderB = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("HQuoteHeaderB"));
				User.HQuoteHeaderE = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("HQuoteHeaderE"));
				User.QuoteMessageB = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("QuoteMessageB"));
				User.QuoteMessageE = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("QuoteMessageE"));
				User.HQuoteMessageB = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("HQuoteMessageB"));
				User.HQuoteMessageE = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("HQuoteMessageE"));
			
				User.ModerationT = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("ModerationT"));
				User.HModerationT = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("HModerationT"));
				User.ModerationU = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("ModerationU"));
				User.HModerationU = Util.Encode(OMSystem.OrkutManager.PrefManager.Get("HModerationU"));
			}
	},

	Bookmark:
	{
		Build:
			function (window, table, prefName, incChk)
			{
				var document = window.document;
                
                if (!OMSystem.OrkutManager.PrefManager.Get("MassUnjoin.Show")) incChk = false;
                if (incChk)
                {
                    var chkAll = document.createElement("input");
                    chkAll.type = "checkbox";
                    chkAll.setAttribute("sel", "false");
                    chkAll.setAttribute("style", "margin-top: 3px; margin-right: 25px;");
                    chkAll.setAttribute("onclick", "var chks = this.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('input'); this.setAttribute('sel', (this.getAttribute('sel') == 'true' ? 'false' : 'true')); for each(var chk in chks) { if (!chk || !chk.getAttribute || chk.getAttribute('type').toLowerCase() != 'checkbox') continue; chk.checked = (this.getAttribute('sel') == 'true'); }");
                    table.getElementsByTagName("th")[0].insertBefore(chkAll, table.getElementsByTagName("th")[0].firstChild);
                }
                
				var cols = table.getElementsByTagName("td");
				for each(var col in cols)
				{
					var has = col.getElementsByTagName("a");
					if (has.length > 0)
					{
						has = has[0];
						if (!has.href.match(/cmm=\d+/i)) continue;
						var Language = OMSystem.OrkutManager.Language.Get();

						// Bookmarks
						var bk = document.createElement("span");
						var check;
						if (prefName == "Bookmarks")
						{
							check = OMSystem.OrkutManager.Util.OMUtil.GetFromArrPref(OMSystem.OrkutManager.PrefManager.Get(prefName, "[]"), has.href.match(/cmm=(\d+)/i)[1]);
						}
						else if (prefName == "Bookmarks.Topic")
						{
							check = OMSystem.OrkutManager.Util.OMUtil.GetFromArrPref(OMSystem.OrkutManager.PrefManager.Get(prefName, "[]"),
								(has.href.match(/cmm=(\d+)/i)[1] + "~" + has.href.match(/&tid=(\d+)/i)[1])
							);
						}
						bk.className = (check) ? "bkOn" : "bkOff";
						bk.addEventListener("click",
							function ()
							{
								var vals = JSON.parse(OMSystem.OrkutManager.PrefManager.Get(prefName, "[]"));
								var nextS = this.nextSibling;
								var check;
								
								if (prefName == "Bookmarks")
								{
									check = (OMSystem.OrkutManager.Util.OMUtil.GetFromArrPref(OMSystem.OrkutManager.PrefManager.Get(prefName, "[]"), nextS.href.match(/cmm=(\d+)/i)[1]));
								}
								else if (prefName == "Bookmarks.Topic")
								{
									check = (OMSystem.OrkutManager.Util.OMUtil.GetFromArrPref(OMSystem.OrkutManager.PrefManager.Get(prefName, "[]"),
										nextS.href.match(/cmm=(\d+)/i)[1] + "~" + nextS.href.match(/&tid=(\d+)/i)[1]
									));
								}

								if (check)
								{
									if (prefName == "Bookmarks")
									{
										vals.splice(vals.indexOf(nextS.href.match(/cmm=(\d+)/i)[1] + "|" + check), 1);
									}
									else if (prefName == "Bookmarks.Topic")
									{
										vals.splice(
											vals.indexOf(nextS.href.match(/cmm=(\d+)/i)[1] + "~" +
												nextS.href.match(/&tid=(\d+)/i)[1] + "|" + check),
											1);
									}

									this.className = "bkOff";
								}
								else
								{
									var cmm, cmmId, tid, tidId;
									var node;
									if (prefName == "Bookmarks")
									{
										cmm = escape(nextS.innerHTML);
										cmmId = nextS.href.match(/cmm=(\d+)/i)[1];
										node = cmmId + "|" + cmm;
									}
									else if (prefName == "Bookmarks.Topic")
									{
										cmm = document.getElementsByClassName("username")[0].getElementsByTagName("a")[0];
										cmm = escape(cmm.innerHTML.replace(/<[^>]*?>/g, ""));
										cmmId = nextS.href.match(/cmm=(\d+)/i)[1];
										tidId = nextS.href.match(/&tid=(\d+)/i)[1];
										tid = escape(nextS.innerHTML);
										node = cmmId + "~" + tidId + "|" + cmm + "~" + tid;
									}
									vals.push(node);
									this.className = "bkOn";
								}
								OMSystem.OrkutManager.PrefManager.Set(prefName, uneval(vals));
							}, false);
						
						col.insertBefore(bk, has);
                        if (incChk)
                        {
                            var omChk = document.createElement("input");
                            omChk.type = "checkbox";
                            omChk.setAttribute("style", "float: left; margin-right: 5px; margin-top:3px;");
                            omChk.name = "omChk";
                            col.insertBefore(omChk, col.firstChild);
                        }
						
						// Last | Forum  (links)
						var divNode = document.createElement("div");
						divNode.style.cssFloat = "right";
						divNode.style.fontSize = "80%";

						var divNodeA = document.createElement("a");
						if (prefName == "Bookmarks")
						{
							divNodeA.href = "/CommTopics?cmm=" + (has.href.match(/cmm=(\d+)/i)[1]) + "&scroll=0";
							divNodeA.innerHTML = "(" + unescape(Language.Forum).toLowerCase() + ")";
						}
						else if (prefName == "Bookmarks.Topic")
						{
							divNodeA.innerHTML = "(" + unescape(Language.Last).toLowerCase() + ")";
							divNodeA.href = has.href + "&na=2&scroll=-1";
						}

						divNode.appendChild(divNodeA);
						col.insertBefore(divNode, col.firstChild);
					}
				}
			},
			
		BuildSingle:
			function (window, node, prefName)
			{
				var document = window.document;
				
				var has = window.location;
				
				var bk = document.createElement("span");
				var check;
				if (prefName == "Bookmarks")
				{
					check = OMSystem.OrkutManager.Util.OMUtil.GetFromArrPref(OMSystem.OrkutManager.PrefManager.Get(prefName, "[]"), has.href.match(/cmm=(\d+)/i)[1]);
				}
				else if (prefName == "Bookmarks.Topic")
				{
					check = OMSystem.OrkutManager.Util.OMUtil.GetFromArrPref(OMSystem.OrkutManager.PrefManager.Get(prefName, "[]"),
						(has.href.match(/cmm=(\d+)/i)[1] + "~" + has.href.match(/&tid=(\d+)/i)[1])
					);
				}
				bk.className = (check) ? "bkOn" : "bkOff";
				
				bk.addEventListener("click",
					function ()
					{
						var vals = JSON.parse(OMSystem.OrkutManager.PrefManager.Get(prefName, "[]"));
						var check;
						var has = window.location;
						if (prefName == "Bookmarks")
						{
							check = OMSystem.OrkutManager.Util.OMUtil.GetFromArrPref(OMSystem.OrkutManager.PrefManager.Get(prefName, "[]"), has.href.match(/cmm=(\d+)/i)[1]);
						}
						else if (prefName == "Bookmarks.Topic")
						{
							check = OMSystem.OrkutManager.Util.OMUtil.GetFromArrPref(OMSystem.OrkutManager.PrefManager.Get(prefName, "[]"),
								(has.href.match(/cmm=(\d+)/i)[1] + "~" + has.href.match(/&tid=(\d+)/i)[1])
							);
						}

						if (check)
						{
							if (prefName == "Bookmarks")
							{
								vals.splice(vals.indexOf(has.href.match(/cmm=(\d+)/i)[1] + "|" + check), 1);
							}
							else if (prefName == "Bookmarks.Topic")
							{
								vals.splice(
									vals.indexOf(has.href.match(/cmm=(\d+)/i)[1] + "~" +
										has.href.match(/&tid=(\d+)/i)[1] + "|" + check),
									1);
							}

							this.className = "bkOff";
						}
						else
						{
							var cmm, cmmId, tid, tidId;
							var node;
							if (prefName == "Bookmarks")
							{
								cmm = escape(this.nextSibling.innerHTML.replace(/<[^>]*?>/g, ""));
								cmmId = has.href.match(/cmm=(\d+)/i)[1];
								node = cmmId + "|" + cmm;
							}
							else if (prefName == "Bookmarks.Topic")
							{
								cmm = document.getElementsByClassName("username")[0].getElementsByTagName("a")[0];
								cmm = escape(cmm.innerHTML.replace(/<[^>]*?>/g, ""));
								cmmId = has.href.match(/cmm=(\d+)/i)[1];
								tidId = has.href.match(/&tid=(\d+)/i)[1];
								tid = escape(this.nextSibling.innerHTML.replace(/<[^>]*?>/g, ""));
								node = cmmId + "~" + tidId + "|" + cmm + "~" + tid;
							}
							vals.push(node);
							this.className = "bkOn";
						}
						OMSystem.OrkutManager.PrefManager.Set(prefName, uneval(vals));
					}, false);
				
				node.parentNode.insertBefore(bk, node);
			},
			
		Sort:
			function (cmm, topic)
			{
				if (cmm)
				{
					var vals = JSON.parse(OMSystem.OrkutManager.PrefManager.Get("Bookmarks"));
					
					function BkSort(l, r)
					{
						var e1 = unescape(l.split("|")[1]);
						var e2 = unescape(r.split("|")[1]);
						return e1 > e2;
					}
					vals.sort(BkSort);
					return vals;
				}
				else if (topic)
				{
					var vals = JSON.parse(OMSystem.OrkutManager.PrefManager.Get("Bookmarks.Topic"));
					
					function BkSort(l, r)
					{
						var e1 = unescape(l.split("|")[1]);
						var e2 = unescape(r.split("|")[1]);
						return e1 > e2;
					}
					vals.sort(BkSort);
					return vals;
				}
				return;
			},
			
		BuildTabCmm:
			function (window, tab)
			{
				var document = window.document;
				var table = document.createElement("table");
				table.cellSpacing = "0";
				table.className = "displaytable";
				
				var vals = OMSystem.OrkutManager.Util.Bookmark.Sort(true);
				
				var colors = new Array("listdark", "listlight");
				var colorI = 0;
				for each(var bk in vals)
				{
					var tr = document.createElement("tr");
					var td = document.createElement("td");
					var td2 = document.createElement("td");
					td.style.width = "70%";
					td2.style.width = "30%";
					
					tr.className = colors[colorI % 2];
					++colorI;
					
					var id = bk.split("|")[0];
					var name = unescape(bk.split("|")[1]);
					
					var a = document.createElement("a");
					a.href = "/Community?cmm=" + id;
					a.innerHTML = name;
					
					td2.innerHTML = id;
					
					td.appendChild(a);
					tr.appendChild(td);
					tr.appendChild(td2);
					table.appendChild(tr);
				}
				
				document.getElementById("subPage" + tab).appendChild(table);
			},
		BuildTabTopic:
			function (window, tab)
			{
				var document = window.document;
				var table = document.createElement("table");
				table.cellSpacing = "0";
				table.className = "displaytable";
				table.style.width = "100%";
				
				var cid = (String(tab).match(/^\d+$/) ? ("subPage" + tab) : tab);
				
				var vals = OMSystem.OrkutManager.Util.Bookmark.Sort(false, true);
				
				var sel = document.getElementById("OMBkTopicSel");
				if (!sel)
				{
					sel = document.createElement("select");
					sel.id = "OMBkTopicSel";
					
					if (cid != tab)
						sel.addEventListener("change",
							function ()
							{
								document.getElementById(cid).removeChild(document.getElementById(cid).getElementsByTagName("table")[0]);
								OMSystem.OrkutManager.Util.Bookmark.BuildTabTopic(window, tab);
								OMSystem.OrkutManager.Util.Bookmark.Build(window, document.getElementById(cid).getElementsByTagName("table")[0], "Bookmarks.Topic");
							}, false);
					
					var inc = [];
					for each(var bk in vals)
					{
						var cmmId = (bk.split("|")[0].split("~")[0]);
						if (inc.indexOf(cmmId) != -1) continue;

						var opt = document.createElement("option");
						opt.value = cmmId;
						opt.innerHTML = unescape(bk.split("|")[1].split("~")[0]);
						sel.appendChild(opt);
						inc.push(cmmId);
					}
					document.getElementById(cid).insertBefore(sel, document.getElementById(cid).firstChild);
				}
				
				var colors = new Array("listdark", "listlight");
				var colorI = 0;
				for each(var bk in vals)
				{
					var cmmId = bk.split("|")[0].split("~")[0];
					if (sel.selectedIndex < 0) continue;
					if (sel.selectedIndex >= 0 && sel.options[sel.selectedIndex].value != cmmId) continue;
					var tr = document.createElement("tr");
					var td = document.createElement("td");
					var td2 = document.createElement("td");
					td.style.width = "70%";
					td2.style.width = "30%";
					
					tr.className = colors[colorI % 2];
					++colorI;
					
					var id = bk.split("|")[0];
					var name = unescape(bk.split("|")[1]);
					
					var a = document.createElement("a");
					a.href = "/CommMsgs?cmm=" + id.replace("~", "&tid=");
					a.innerHTML = name.split("~")[1];
					
					td2.innerHTML = "<span title='" + (id.split("~")[0]) + "'>" + (id.split("~")[1]) + "</span>";
					
					td.appendChild(a);
					tr.appendChild(td);
					tr.appendChild(td2);
					table.appendChild(tr);
				}
				
				document.getElementById(cid).appendChild(table);
			}
	},

	Updater:
	{
		Update :
			function (window, url, cmm)
			{
				var document = window.document;
				
				var Ajax = OMSystem.OrkutManager.Util.Ajax;
				
				function Index(name, time, count)
				{
					this.name = name;
					this.time = time;
					this.count = count;
				}
				var i;
				
				var type = 0;
				var otherparams = "";
				switch (url.toLowerCase())
				{
					case "communities":
						i = new Index(0, 1, 2);
						type = 0;
						break;
					case "community":
						i = new Index(1, 3, 2);
						type = 1;
						break;
					case "commtopics":
						i = new Index(1, 4, 3);
						type = 2;
						var nid;
						try{ nid = window.location.href.match(/&nid=(\d+-\d+-\d+)/)[1]; }catch(ex){}
						if (nid)
							otherparams = "&na=" + window.location.href.match(/&na=(\d+)/)[1] +
								"&nid=" + window.location.href.match(/&nid=(\d+-\d+-\d+)/)[1];
						break;
				}
				oUpdate = Ajax.Get(window);
				Ajax.Request("/" + url + "?cmm=" + cmm + otherparams, oUpdate,
					function ()
					{
						var o = oUpdate;
						if (o.readyState != 4) return;

						var xml = document.createElement("div");
						xml.innerHTML = o.responseText;
						
						var oldTb;
						var newTb;
						try
						{
							switch (type)
							{
								case 0:
									oldTb = document.getElementById("subPage0").getElementsByTagName("table")[0];
									newTb = xml.getElementsByClassName("displaytable")[0];
									break;
								case 1:
								case 2:
									oldTb = document.getElementsByName("topicsForm")[0].getElementsByTagName("table")[0];
									var frms = xml.getElementsByTagName("form");
									var frmE = null;
									for each(var frm in frms)
									{
										if (frm.name == "topicsForm")
										{
											frmE = frm;
											break;
										}
									}
									newTb = frmE.getElementsByTagName("table")[0];
									break;
							}
						}
						catch (ex) { return; }
						
						// Check for changes
						try
						{
							function Block()
							{
								this.cmm = 0;
								this.tid = 0;
								this.time = 0;
								this.memb = 0;
								this.isNew = false;
							}
							var trs = oldTb.getElementsByTagName("tr");
							var blocks = [];
							for each(var tr in trs)
							{
								var block = tr.getElementsByTagName("td");
								if (block.length <= 0) continue;
								var obj = new Block();
								obj.cmm = block[i.name].getElementsByTagName("a")[0].href.match(/cmm=(\d+)/i)[1];
								try {
									obj.tid = block[i.name].getElementsByTagName("a")[0].href.match(/&tid=(\d+)/i)[1];
								} catch(ex) {}
								obj.time = block[i.time].innerHTML.replace(/\s/g, "")
								obj.memb = block[i.count].innerHTML.replace(/^\s|\s$/g, "").replace(/\.|,/g, "");
								obj.isNew = (block[i.name].getElementsByClassName("omNew").length > 0);
								blocks.push(obj);
							}
							var trs = newTb.getElementsByTagName("tr");
							for each(var tr in trs)
							{
								var block = tr.getElementsByTagName("td");
								if (block.length <= 0) continue;
								var newobj = new Block();
								var cmmLink = block[i.name].getElementsByTagName("a")[0];
								cmmLink.href = cmmLink.href.replace(/\/Main#/, "/");
								newobj.cmm = cmmLink.href.match(/cmm=(\d+)/i)[1];
								try {
									newobj.tid = cmmLink.href.match(/&tid=(\d+)/i)[1];
								} catch(ex) {}
								newobj.time = block[i.time].innerHTML.replace(/\s/g, "")
								newobj.memb = block[i.count].innerHTML.replace(/\s/g, "").replace(/\.|,/g, "");
								var oldobj = blocks.filter(
									function (o)
									{
										if (type == 0) return (o.cmm == newobj.cmm)
										else return (o.tid == newobj.tid);
									});
								var hasOld = false;
								if (oldobj.length > 0)
								{
									hasOld = true;
									oldobj = oldobj[0];
								}
								
								// Time watch
								var isNew = false;
								
								if (hasOld)
								{
								if (type == 0)
								{
									var newTimeblock = newobj.time.match(/(\d{1,2}):(\d{1,2})\s?(am|pm)?/i);
									var oldTimeblock = oldobj.time.match(/(\d{1,2}):(\d{1,2})\s?(am|pm)?/i);
									if (newTimeblock)
									{
										isNew = oldobj.isNew;
										if (oldTimeblock && !isNew)
										{
											var newHour = (newTimeblock.length == 4 && (("" + newTimeblock[3]).toLowerCase()) == "pm") ?
												(newTimeblock[1] + 12) :
												newTimeblock[1];
											var newMinute = newTimeblock[2];
											
											var oldHour = (oldTimeblock.length == 4 && (("" + oldTimeblock[3]).toLowerCase()) == "pm") ?
												(oldTimeblock[1] + 12) :
												oldTimeblock[1];
											var oldMinute = oldTimeblock[2];
											
											var newDt = new Date();
											newDt.setHours(newHour);
											newDt.setMinutes(newMinute);
											var oldDt = new Date();
											oldDt.setHours(oldHour);
											oldDt.setMinutes(oldMinute);

											if ((newDt - oldDt) > 0) isNew = true;
											newHour = null;
											newMinute = null;
											oldHour = null;
											oldMinute = null;
										}
										else isNew = true;
									}
								}
								else
								{
									isNew = (newobj.memb > oldobj.memb);
									if (!isNew)
										isNew = oldobj.isNew;
								}
								}
								else isNew = true;

								if (isNew)
									block[i.name].innerHTML = "<span class='omNew'>&nbsp;</span>" + block[i.name].innerHTML;
								
								if (hasOld)
								{
									if (type == 0)
									{
										// Member count
										if (newobj.memb > parseInt(oldobj.memb))
											block[i.count].innerHTML += "<span style='color:green;'>(+)</span>";
										else if (newobj.memb < parseInt(oldobj.memb))
											block[i.count].innerHTML += "<span style='color:red;'>(-)</span>";
										else
											block[i.count].innerHTML += oldobj.memb.match(/<span[^$]+/i) || "";
									}
								}
							}
						}
						catch(ex){ }
						
						blocks = null; trs = null; obj = null; newobj = null;
						
						oldTb.parentNode.insertBefore(newTb, oldTb);
						var prefName = (type == 0 ? "Bookmarks" : "Bookmarks.Topic");
						OMSystem.OrkutManager.Util.Bookmark.Build(window, newTb, prefName, (type == 0));
						oldTb.parentNode.removeChild(oldTb);

						oUpdate = null;
					}, window
				);
			}
	}
};

